import { well } from "./tooler";
import { writeFile } from 'fs/promises';
import axios from 'axios';
import { Db, MongoClient, ObjectId } from "mongodb";

let url = 'https://www8.garmin.com/manuals-apac/webhelp/forerunner245245music/ZH-TW/static/images/temp/logo.png';

async function writeToFile() {
    const t = (new Date()).toGMTString();
    console.log("oks", t);
    await writeFile("./assets/" + Date.now() + ".txt", 'hello ' + t);
}

async function download(url) {
    try {
        const res = await axios.get(url, { responseType: 'arraybuffer' });
        const name = Date.now() + ".jpg";
        writeFile(name, res.data);
        console.log("download over")
        return name;
    }
    catch (e) {
        console.log(e);
        return "0";
    }

}

async function link() {
    const link = "mongodb://admin:jsz04005301@120.48.63.39:27017";
    const client = new MongoClient(link);
    await client.connect();
    console.log("Connected successfully to server!");
    const db = client.db("book");
    const collection = db.collection("video");
    const temp = await collection.find({ img: { $exists: false } }).toArray();
    const total = temp.length;
    console.log("total", total);
    let i = 0;

    do {
        const obj = await collection.find({ img: { $exists: false } }).limit(1).toArray();
        console.log(i, "start");
        console.log(obj);

        if (obj.length) {
            const name = await download(obj[0].poster);
            console.log(name);

            await collection.updateOne({ _id: new ObjectId(obj[0]._id) }, { $unset: { pic: "" }, $set: { img: name } });
            // console.log("2 type of ", typeof res);
            // console.log(JSON.stringify(res));
            console.log(i + "/" + total + " ---- over")
        }
        else {
            break;
        }
    } while (++i <= total)

}


// writeToFile();
// download(url);
// link();
loops();
function loops() {
    writeToFile();
    setTimeout(loops, 10000);
}

// console.log(well)